package com.lzb.musicplayer.utils;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.provider.Settings;

import com.blankj.utilcode.util.ToastUtils;
import com.lzb.musicplayer.dialog.ReqPermissionDialog;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

public class RingtoneUtil {

    /**
     * 设置音频为铃声
     * @param context 上下文
     * @param audioPath 音频文件路径
     * @param ringtoneType 铃声类型 (RingtoneManager.TYPE_RINGTONE, TYPE_NOTIFICATION, TYPE_ALARM)
     */
    public static void setRingtone(Context context, String audioPath, int ringtoneType) {
        try {
            // 检查权限
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (!Settings.System.canWrite(context)) {
                    ReqPermissionDialog reqPermissionDialog = new ReqPermissionDialog(context);
                    reqPermissionDialog.setListener(new ReqPermissionDialog.Ilistener() {
                        @Override
                        public void clickConfirm() {
                            // 引导用户到设置页面开启权限
                            Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
                            intent.setData(Uri.parse("package:" + context.getPackageName()));
                            context.startActivity(intent);
//                            ToastUtils.showShort("请开启修改系统设置的权限");
                        }
                    });
                    reqPermissionDialog.show();
                    return;
                }
            }

            File audioFile = new File(audioPath);
            if (!audioFile.exists()) {
                ToastUtils.showShort("音频文件不存在");
                return;
            }

            ContentResolver resolver = context.getContentResolver();
            Uri newUri = null;

            // 对于Android 10及以上版本，使用新的方法
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                // 创建ContentValues用于插入媒体库
                ContentValues values = new ContentValues();
                values.put(MediaStore.Audio.Media.DISPLAY_NAME, audioFile.getName());
                values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/mp3");
                values.put(MediaStore.Audio.Media.TITLE, audioFile.getName());
                values.put(MediaStore.Audio.Media.ARTIST, "Music Player");
                values.put(MediaStore.Audio.Media.IS_RINGTONE, ringtoneType == RingtoneManager.TYPE_RINGTONE);
                values.put(MediaStore.Audio.Media.IS_NOTIFICATION, ringtoneType == RingtoneManager.TYPE_NOTIFICATION);
                values.put(MediaStore.Audio.Media.IS_ALARM, ringtoneType == RingtoneManager.TYPE_ALARM);
                values.put(MediaStore.Audio.Media.IS_MUSIC, false);
                values.put(MediaStore.Audio.Media.RELATIVE_PATH, Environment.DIRECTORY_RINGTONES);

                // 插入到媒体库
                Uri collection = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                newUri = resolver.insert(collection, values);

                if (newUri != null) {
                    // 复制文件内容到媒体库
                    try (OutputStream outputStream = resolver.openOutputStream(newUri);
                         FileInputStream inputStream = new FileInputStream(audioFile)) {
                        if (outputStream != null) {
                            byte[] buffer = new byte[8192];
                            int bytesRead;
                            while ((bytesRead = inputStream.read(buffer)) != -1) {
                                outputStream.write(buffer, 0, bytesRead);
                            }
                        }
                    }
                }
            } else {
                // Android 9及以下版本使用传统方法
                ContentValues values = new ContentValues();
                values.put(MediaStore.MediaColumns.DATA, audioFile.getAbsolutePath());
                values.put(MediaStore.MediaColumns.TITLE, audioFile.getName());
                values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
                values.put(MediaStore.Audio.Media.ARTIST, "Music Player");
                values.put(MediaStore.Audio.Media.IS_RINGTONE, ringtoneType == RingtoneManager.TYPE_RINGTONE);
                values.put(MediaStore.Audio.Media.IS_NOTIFICATION, ringtoneType == RingtoneManager.TYPE_NOTIFICATION);
                values.put(MediaStore.Audio.Media.IS_ALARM, ringtoneType == RingtoneManager.TYPE_ALARM);
                values.put(MediaStore.Audio.Media.IS_MUSIC, false);

                Uri uri = MediaStore.Audio.Media.getContentUriForPath(audioFile.getAbsolutePath());
                
                // 先删除已存在的记录
                Cursor cursor = resolver.query(uri, null, MediaStore.MediaColumns.DATA + "=?", 
                        new String[]{audioFile.getAbsolutePath()}, null);
                if (cursor != null && cursor.moveToFirst()) {
                    String id = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.MediaColumns._ID));
                    resolver.delete(Uri.withAppendedPath(uri, id), null, null);
                }
                if (cursor != null) {
                    cursor.close();
                }

                // 插入新的记录
                newUri = resolver.insert(uri, values);
            }

            if (newUri == null) {
                ToastUtils.showShort("铃声设置失败");
                return;
            }

            // 设置为默认铃声
            RingtoneManager.setActualDefaultRingtoneUri(context, ringtoneType, newUri);
            
            String typeName = getRingtoneTypeName(ringtoneType);
            ToastUtils.showShort("已设置为" + typeName);
            
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtils.showShort("铃声设置失败: " + e.getMessage());
        }
    }

    /**
     * 分配铃声给联系人
     * @param context 上下文
     * @param audioPath 音频文件路径
     */
    public static void assignRingtoneToContact(Context context, String audioPath) {
        try {
            File audioFile = new File(audioPath);
            if (!audioFile.exists()) {
                ToastUtils.showShort("音频文件不存在");
                return;
            }

            ContentResolver resolver = context.getContentResolver();
            Uri newUri = null;

            // 对于Android 10及以上版本，使用新的方法
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                // 创建ContentValues用于插入媒体库
                ContentValues values = new ContentValues();
                values.put(MediaStore.Audio.Media.DISPLAY_NAME, audioFile.getName());
                values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/mp3");
                values.put(MediaStore.Audio.Media.TITLE, audioFile.getName());
                values.put(MediaStore.Audio.Media.ARTIST, "Music Player");
                values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
                values.put(MediaStore.Audio.Media.IS_MUSIC, false);
                values.put(MediaStore.Audio.Media.RELATIVE_PATH, Environment.DIRECTORY_RINGTONES);

                // 插入到媒体库
                Uri collection = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                newUri = resolver.insert(collection, values);

                if (newUri != null) {
                    // 复制文件内容到媒体库
                    try (OutputStream outputStream = resolver.openOutputStream(newUri);
                         FileInputStream inputStream = new FileInputStream(audioFile)) {
                        if (outputStream != null) {
                            byte[] buffer = new byte[8192];
                            int bytesRead;
                            while ((bytesRead = inputStream.read(buffer)) != -1) {
                                outputStream.write(buffer, 0, bytesRead);
                            }
                        }
                    }
                }
            } else {
                // Android 9及以下版本使用传统方法
                ContentValues values = new ContentValues();
                values.put(MediaStore.MediaColumns.DATA, audioFile.getAbsolutePath());
                values.put(MediaStore.MediaColumns.TITLE, audioFile.getName());
                values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
                values.put(MediaStore.Audio.Media.ARTIST, "Music Player");
                values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
                values.put(MediaStore.Audio.Media.IS_MUSIC, false);

                Uri uri = MediaStore.Audio.Media.getContentUriForPath(audioFile.getAbsolutePath());
                
                // 先删除已存在的记录
                Cursor cursor = resolver.query(uri, null, MediaStore.MediaColumns.DATA + "=?", 
                        new String[]{audioFile.getAbsolutePath()}, null);
                if (cursor != null && cursor.moveToFirst()) {
                    String id = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.MediaColumns._ID));
                    resolver.delete(Uri.withAppendedPath(uri, id), null, null);
                }
                if (cursor != null) {
                    cursor.close();
                }

                // 插入新的记录
                newUri = resolver.insert(uri, values);
            }

            if (newUri == null) {
                ToastUtils.showShort("联系人铃声设置失败");
                return;
            }

            // 打开联系人选择界面
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
            intent.putExtra("ringtoneUri", newUri.toString());
            
            // 注意：这里需要Activity的startActivityForResult，所以需要在Activity中处理
            // 暂时提示用户手动设置
            ToastUtils.showShort("请在联系人详情中手动设置铃声");
            
            // 打开系统联系人应用
            Intent contactIntent = new Intent(Intent.ACTION_VIEW);
            contactIntent.setType(ContactsContract.Contacts.CONTENT_TYPE);
            context.startActivity(contactIntent);
            
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtils.showShort("联系人铃声设置失败: " + e.getMessage());
        }
    }

    /**
     * 获取铃声类型名称
     */
    private static String getRingtoneTypeName(int ringtoneType) {
        switch (ringtoneType) {
            case RingtoneManager.TYPE_RINGTONE:
                return "标准铃声";
            case RingtoneManager.TYPE_NOTIFICATION:
                return "通知声音";
            case RingtoneManager.TYPE_ALARM:
                return "报警声";
            default:
                return "铃声";
        }
    }
}